<template>
    <div>books
        <button @click="addBook">添加</button>
        <Table :bookList="bookList">
            <template #book="{row}">
                <td>{{ row.id }}</td>
                <td>{{ row.bookname}}</td>
                <td>{{ row.author}}</td>
                <td>{{ row.publisher}}</td>
                <td>
                    <button @click="doDel(row.id)">删除</button>
                    <button @click="doEdit(row)">修改</button>
                </td>
            </template>
        </Table>
        <Dialog v-show="showDialog" :showDialog.sync="showDialog" :isEdit="isEdit" @update="doUpdate">
          <template>
            <form>
            bookname: <input type="text" v-model="formData.bookname"><br/>
            author:<input type="text" v-model="formData.author"><br/>
            publisher:<input type="text" v-model="formData.publisher"><br/>
           </form>
          </template>
        </Dialog>
    </div>
</template>

<script>
import Table from '@/views/table.vue'
import Dialog from '@/views/Dialog.vue'
import axios from 'axios'
export default {
  name: 'Books-list',
  components: {
    Table, Dialog
  },
  data () {
    return {
      bookList: [],
      showDialog: false,
      isEdit: false,
      formData: {
        bookname: '',
        author: '',
        publisher: ''
      },
      id: ''
    }
  },
  async created () {
    await this.getBook()
  },
  mounted () {

  },

  methods: {
    async getBook () {
      const res = await axios.get('http://ajax-api.itheima.net/api/books')
      this.bookList = (res.data.data)
    },
    addBook () {
      this.isEdit = !this.isEdit
      this.showDialog = !this.showDialog
    },
    doEdit (row) {
      this.showDialog = true
      this.isEdit = false
      this.formData = { ...row }
      this.id = row.id
    },
    async handleEdit () {
      console.log(this.id)
      const res = await axios({
        url: `http://ajax-api.itheima.net/api/books/${this.id}`,
        method: 'put',
        data: this.formData
      })
      console.log(res)
    },
    async doAdd () {
      const res = await axios({
        url: 'http://ajax-api.itheima.net/api/books',
        method: 'post',
        data: this.formData
      })
      console.log(res)
    },
    async doUpdate () {
      if (!this.formData.bookname.trim()) return alert('请输入bookname')
      if (!this.formData.author.trim()) return alert('请输入author')
      if (!this.formData.publisher.trim()) return alert('请输入publisher')
      this.isEdit ? await this.doAdd() : await this.handleEdit()
      await this.getBook()
      this.showDialog = false
    },
    async doDel (id) {
      if (confirm('你确认删除吗?')) {
        await axios({
          url: `http://ajax-api.itheima.net/api/books/${id}`,
          method: 'delete'
        })
      }
      await this.getBook()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
